import json
import time
from pymysql.converters import escape_string
import SQL_CRUD_Interface
import Tools_Interface
import re
import requests
# 引入模块
import os


def mkdir(path):
    # 去除首位空格
    path = path.strip()
    # 去除尾部 \ 符号
    path = path.rstrip("\\")
    # 判断路径是否存在
    # 存在     True
    # 不存在   False
    isExists = os.path.exists(path)
    # 判断结果
    if not isExists:
        # 如果不存在则创建目录
        # 创建目录操作函数
        os.makedirs(path)
        print(path + ' 创建成功')
        return True
    else:
        # 如果目录存在则不创建，并提示目录已存在
        print(path + ' 目录已存在')
        return False


name = " --- name ---"


def get_audio_path(english):
    audio_folder = r"C:\Users\QAQ\Desktop\english-forgetting-curve\django\static\english_audio"
    english = english.strip()
    folder_name = english[0]
    folder_path = audio_folder + "\\" + folder_name
    english_audio_url = folder_path + "\\" + english + ".MP3"
    return folder_path, english_audio_url



def DownloadAudio(english):
    realUrl = "http://dict.youdao.com/dictvoice?audio={}&type=2".format(english)

    resp = get_audio_path(english)
    mkdir(resp[0])

    # ('C:\\Users\\QAQ\\Desktop\\python_tools\\english_audio\\b',
    #  'C:\\Users\\QAQ\\Desktop\\python_tools\\english_audio\\b\\bpple.MP3')
    print(resp[0])
    print(resp[1])

    r = requests.get(realUrl)
    if r.status_code == 200:
        with open(resp[1], "wb") as f:
            f.write(r.content)
            print("ok: {}".format(realUrl))
    else:
        print("不存在: {}".format(name))


def get_complexity(eng):
    try:
        sql = '  select complexity from tb_word  where english = "%s"     limit 0,333;   ' % eng
        result =  SQL_CRUD_Interface.select_interface('study_english_database', sql )
        return result[0]
    except:
        print("errrrrrrrror")

def get_words(day):
    try:
        sql = '  select `english` from tb_word_2    where day = "%s"      ' % str(day)
        result = SQL_CRUD_Interface.select_interface('study_english_database', sql )
        return result
    except:
        print("errrrrrrrror")




def start():
    for ii in range(88, 296):
        print("=================   now index is :   ii =    " + str(ii))
        words = get_words(ii)
        print(words)
        for ii in words:
            eng = ii[0]
            complex__ = get_complexity(eng)
            res = get_audio_path(eng)
            if complex__[0] > 51:
                isExists = os.path.exists(res[1])
                if isExists:
                    print("音频文件已经存在了...")
                else:
                    print("sleeping...")
                    print(eng)
                    time.sleep(Tools_Interface.get_random_number(5,9))
                    DownloadAudio(eng)


if __name__ == '__main__':
    start()











